package com.flow.framework.mq.service.system.health.impl;

import com.flow.framework.common.health.ServiceHealthCheckCode;
import com.flow.framework.common.pojo.vo.system.ServiceHealthVo;
import com.flow.framework.common.service.system.health.IHealthCheckService;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.system.helper.SystemHealthHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.Collections;
import java.util.List;

/**
 * mq健康检查
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/3/26
 */
@Slf4j
@RequiredArgsConstructor
public class QueueHealthCheckServiceImpl implements IHealthCheckService {

    private final RabbitTemplate rabbitTemplate;

    /**
     * @inheritDoc
     */
    @Override
    public List<ServiceHealthVo> check() {
        try {
            String version = rabbitTemplate
                    .execute((channel) -> channel.getConnection().getServerProperties().get("version").toString());
            if (VerifyUtil.isEmpty(version)) {
                log.error("mq server status error. version : {}", version);
                return Collections.singletonList(
                        SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_MQ_CODE, null, null)
                );
            }
            return Collections.singletonList(SystemHealthHelper.healthy(ServiceHealthCheckCode.SERVICE_MQ_CODE));
        } catch (Exception e) {
            log.error("check mq error.", e);
            return Collections.singletonList(
                    SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_MQ_CODE, e.getMessage(), null)
            );
        }
    }
}
